<template>
  <div class="chat-container">
    <!-- 左侧用户列表 -->
    <div class="user-list">
      <div class="list-header">
        <h3>消息列表</h3>
        <el-button 
          :icon="EditPen" 
          circle 
          size="small" 
          @click="showNewChatDialog = true"
        />
      </div>

      <el-input
        v-model="searchKeyword"
        placeholder="搜索用户..."
        clearable
        class="search-input"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <div class="conversations-list">
        <div
          v-for="conv in filteredConversations"
          :key="conv.id"
          :class="['conversation-item', { active: selectedConversation?.id === conv.id }]"
          @click="selectConversation(conv)"
        >
          <el-avatar :size="45" :src="conv.other_user?.avatar">
            {{ conv.other_user?.nickname?.charAt(0) || 'U' }}
          </el-avatar>
          <div class="conversation-info">
            <div class="conversation-header">
              <span class="user-name">{{ conv.other_user?.nickname || '未知用户' }}</span>
              <span class="time">{{ formatTime(conv.last_message_at) }}</span>
            </div>
            <div class="conversation-footer">
              <span class="last-message">{{ conv.last_message?.content || '暂无消息' }}</span>
              <el-badge 
                v-if="conv.unread_count > 0" 
                :value="conv.unread_count" 
                class="unread-badge"
              />
            </div>
          </div>
        </div>

        <el-empty 
          v-if="conversations.length === 0" 
          description="暂无会话"
          :image-size="80"
        />
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-area">
      <template v-if="selectedConversation">
        <!-- 聊天头部 -->
        <div class="chat-header">
          <el-button 
            :icon="ArrowLeft" 
            circle 
            text 
            @click="goToHome"
            class="back-button"
          />
          <div class="chat-user-info">
            <el-avatar :size="40" :src="selectedConversation.other_user?.avatar">
              {{ selectedConversation.other_user?.nickname?.charAt(0) || 'U' }}
            </el-avatar>
            <div class="user-details">
              <h4>{{ selectedConversation.other_user?.nickname || '未知用户' }}</h4>
            </div>
          </div>

        </div>

        <!-- 聊天消息区域 -->
        <div ref="messageContainer" class="messages-container">
          <div v-for="msg in messages" :key="msg.id" :class="['message-item', msg.sender_id === currentUserId ? 'sent' : 'received']">
            <el-avatar 
              :size="36" 
              :src="msg.sender_id === currentUserId ? currentUser?.avatar : selectedConversation.other_user?.avatar"
            >
              {{ msg.sender_id === currentUserId ? (currentUser?.nickname?.charAt(0) || 'M') : (selectedConversation.other_user?.nickname?.charAt(0) || 'U') }}
            </el-avatar>
            <div class="message-content">
              <div class="message-bubble">
                {{ msg.content }}
              </div>
              <div class="message-time">{{ formatMessageTime(msg.created_at) }}</div>
            </div>
          </div>

          <div v-if="messages.length === 0" class="empty-messages">
            <el-empty description="暂无消息，开始聊天吧！" :image-size="100" />
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <div class="input-box">
            <el-input
              v-model="messageInput"
              type="textarea"
              :rows="3"
              placeholder="输入消息..."
              @keydown.enter.exact.prevent="sendMessage"
              @keydown.ctrl.enter.exact="messageInput += '\n'"
            />
            <el-button 
              type="primary" 
              :icon="Promotion" 
              :loading="sending"
              @click="sendMessage"
            >
              发送
            </el-button>
          </div>
          <div class="input-hint">
            按 Enter 发送，Ctrl+Enter 换行
          </div>
        </div>
      </template>

      <!-- 未选择会话 -->
      <div v-else class="no-conversation">
        <el-button 
          :icon="ArrowLeft" 
          circle 
          text 
          @click="goToHome"
          class="back-button"
        />
        <el-empty description="选择一个会话开始聊天" :image-size="200">
          <el-button type="primary" @click="showNewChatDialog = true">
            <el-icon><ChatDotRound /></el-icon>
            新建会话
          </el-button>
        </el-empty>
      </div>
    </div>

    <!-- 新建会话对话框 -->
    <el-dialog
      v-model="showNewChatDialog"
      title="选择聊天对象"
      width="500px"
    >
      <el-input
        v-model="userSearchKeyword"
        placeholder="搜索用户..."
        clearable
        class="search-input"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <div class="user-select-list">
        <div
          v-for="user in filteredUsers"
          :key="user.user_id"
          class="user-select-item"
          @click="startNewChat(user)"
        >
          <el-avatar :size="40" :src="user.avatar">
            {{ user.nickname?.charAt(0) || 'U' }}
          </el-avatar>
          <div class="user-info">
            <div class="user-name">{{ user.nickname || '未知用户' }}</div>
            <div class="user-email">{{ user.email }}</div>
          </div>
        </div>

        <el-empty 
          v-if="users.length === 0" 
          description="暂无其他用户"
          :image-size="80"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import {
  Search,
  EditPen,
  MoreFilled,
  Picture,
  Paperclip,
  Promotion,
  ChatDotRound,
  ArrowLeft
} from '@element-plus/icons-vue'
import request from '@/utils/request'
import { useSocket } from '@/composables/useSocket'

// 路由实例
const router = useRouter()

// WebSocket
const {
  connect,
  disconnect,
  sendMessage: sendSocketMessage,
  onNewMessage,
  onUserTyping,
  isConnected
} = useSocket()

// 当前用户信息
const currentUser = ref(null)
const currentUserId = ref(null)

// 会话列表
const conversations = ref([])
const selectedConversation = ref(null)

// 消息列表
const messages = ref([])
const messageInput = ref('')
const sending = ref(false)

// 用户列表
const users = ref([])
const searchKeyword = ref('')
const userSearchKeyword = ref('')
const showNewChatDialog = ref(false)

// 消息容器引用
const messageContainer = ref(null)

// 计算属性 - 过滤会话列表
const filteredConversations = computed(() => {
  if (!searchKeyword.value) return conversations.value
  return conversations.value.filter(conv => 
    conv.other_user?.nickname?.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 计算属性 - 过滤用户列表
const filteredUsers = computed(() => {
  if (!userSearchKeyword.value) return users.value
  return users.value.filter(user =>
    user.nickname?.toLowerCase().includes(userSearchKeyword.value.toLowerCase()) ||
    user.email?.toLowerCase().includes(userSearchKeyword.value.toLowerCase())
  )
})

// 返回首页方法
const goToHome = () => {
  router.push('/')
}

// 获取当前用户信息
const getCurrentUser = async () => {
  try {
    const response = await request.get('/user/current')
    if (response.code === 0) {
      currentUser.value = response.data
      currentUserId.value = response.data.user_id
    }
  } catch (error) {
    console.error('获取当前用户信息失败:', error)
  }
}

// 获取会话列表
const loadConversations = async () => {
  try {
    const response = await request.get('/conversations')
    if (response.code === 0) {
      conversations.value = response.data.list || []
    }
  } catch (error) {
    console.error('获取会话列表失败:', error)
    ElMessage.error('获取会话列表失败')
  }
}

// 获取用户列表(排除当前用户)
const loadUsers = async () => {
  try {
    const response = await request.get('/users', {
      params: {
        pageSize: 100
      }
    })
    if (response.code === 0) {
      // 排除当前用户
      users.value = (response.data.list || []).filter(
        user => user.user_id !== currentUserId.value
      )
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

// 选择会话
const selectConversation = async (conversation) => {
  selectedConversation.value = conversation
  await loadMessages(conversation.id)
  
  // 重置未读计数
  if (conversation.unread_count > 0) {
    try {
      await request.post(`/conversations/${conversation.id}/reset-unread`)
      conversation.unread_count = 0
    } catch (error) {
      console.error('重置未读计数失败:', error)
    }
  }
}

// 加载消息列表
const loadMessages = async (conversationId) => {
  try {
    const response = await request.get(`/conversations/${conversationId}/messages`, {
      params: {
        pageSize: 50
      }
    })
    if (response.code === 0) {
      messages.value = response.data.list || []
      await nextTick()
      scrollToBottom()
    }
  } catch (error) {
    console.error('获取消息列表失败:', error)
    ElMessage.error('获取消息列表失败')
  }
}

// 发送消息 - WebSocket版本
const sendMessage = async () => {
  if (!messageInput.value.trim()) {
    ElMessage.warning('请输入消息内容')
    return
  }

  if (!selectedConversation.value) {
    ElMessage.warning('请先选择聊天对象')
    return
  }

  sending.value = true
  try {
    // 使用WebSocket发送
    const message = await sendSocketMessage({
      receiver_id: selectedConversation.value.other_user.user_id,
      content: messageInput.value.trim(),
      message_type: 'text'
    })

    // 添加到消息列表
    messages.value.push(message)
    messageInput.value = ''
    
    await nextTick()
    scrollToBottom()
    
    // 刷新会话列表
    await loadConversations()
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败')
  } finally {
    sending.value = false
  }
}

// 开始新对话
const startNewChat = async (user) => {
  try {
    const response = await request.post('/conversations', {
      target_user_id: user.user_id
    })

    if (response.code === 0) {
      showNewChatDialog.value = false
      userSearchKeyword.value = ''
      
      // 刷新会话列表
      await loadConversations()
      
      // 选中新建的会话
      const newConv = conversations.value.find(
        c => c.other_user?.user_id === user.user_id
      )
      if (newConv) {
        selectConversation(newConv)
      }
    }
  } catch (error) {
    console.error('创建会话失败:', error)
    ElMessage.error('创建会话失败')
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messageContainer.value) {
    messageContainer.value.scrollTop = messageContainer.value.scrollHeight
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now - date

  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  if (diff < 604800000) return `${Math.floor(diff / 86400000)}天前`
  
  return date.toLocaleDateString()
}

// 格式化消息时间
const formatMessageTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

// 监听会话变化
watch(showNewChatDialog, (newVal) => {
  if (newVal) {
    loadUsers()
  }
})

// 组件挂载时初始化
onMounted(async () => {
  await getCurrentUser()
  await loadConversations()
  
  // 连接WebSocket
  const token = localStorage.getItem('token')
  if (token) {
    connect(token)
    
    // 监听新消息
    onNewMessage((message) => {
      // 如果是当前会话的消息,添加到列表
      if (selectedConversation.value) {
        const isCurrentConversation = 
          (message.sender_id === selectedConversation.value.other_user.user_id && 
           message.receiver_id === currentUserId.value) ||
          (message.receiver_id === selectedConversation.value.other_user.user_id && 
           message.sender_id === currentUserId.value)
        
        if (isCurrentConversation) {
          messages.value.push(message)
          nextTick(() => {
            scrollToBottom()
          })
        }
      }
      
      // 刷新会话列表
      loadConversations()
    })
    
    // 监听对方正在输入
    onUserTyping((data) => {
      if (selectedConversation.value && 
          data.user_id === selectedConversation.value.other_user.user_id) {
        console.log('对方正在输入...')
        // 可以在这里显示"正在输入..."提示
      }
    })
  }
})

// 组件卸载时断开WebSocket
onUnmounted(() => {
  disconnect()
})
</script>

<style scoped>
.chat-container {
  display: flex;
  height: calc(100vh - 64px);
  background: #f5f7fa;
}

/* 左侧用户列表 */
.user-list {
  width: 320px;
  background: #fff;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
}

.list-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.search-input {
  margin: 16px 20px;
  width: 280px;
}

.conversations-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

.conversation-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 20px;
  cursor: pointer;
  transition: background 0.3s;
}

.conversation-item:hover {
  background: #f5f7fa;
}

.conversation-item.active {
  background: #ecf5ff;
}

.conversation-info {
  flex: 1;
  min-width: 0;
}

.conversation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.user-name {
  font-size: 15px;
  font-weight: 500;
  color: #303133;
}

.time {
  font-size: 12px;
  color: #909399;
}

.conversation-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.last-message {
  font-size: 13px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

/* 右侧聊天区域 */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #e4e7ed;
  background: #fff;
  position: relative;
  padding-left: 56px;
}

.back-button {
  position: absolute;
  left: 16px;
  top: 50%;
  transform: translateY(-50%);
}

.chat-user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  color: #303133;
}

.user-status {
  font-size: 12px;
  color: #67c23a;
}

/* 消息容器 */
.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f5f7fa;
}

.message-item {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.message-item.sent {
  flex-direction: row-reverse;
}

.message-content {
  max-width: 60%;
  display: flex;
  flex-direction: column;
}

.message-item.sent .message-content {
  align-items: flex-end;
}

.message-bubble {
  padding: 12px 16px;
  border-radius: 8px;
  word-break: break-word;
  line-height: 1.5;
}

.message-item.received .message-bubble {
  background: #fff;
  color: #303133;
}

.message-item.sent .message-bubble {
  background: #409eff;
  color: #fff;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  padding: 0 4px;
}

.empty-messages {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

/* 输入区域 */
.input-area {
  border-top: 1px solid #e4e7ed;
  background: #fff;
  padding: 16px 24px;
}

.input-toolbar {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.input-box {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.input-box :deep(.el-textarea) {
  flex: 1;
}

.input-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  text-align: right;
}

/* 未选择会话 */
.no-conversation {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.no-conversation .back-button {
  top: 20px;
  left: 20px;
  transform: none;
}

/* 用户选择列表 */
.user-select-list {
  max-height: 500px;
  overflow-y: auto;
  margin-top: 16px;
}

.user-select-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: background 0.3s;
}

.user-select-item:hover {
  background: #f5f7fa;
}

.user-info {
  flex: 1;
}

.user-info .user-name {
  font-size: 15px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}
</style>